<template>
  <div>
    <header class="header">
      <el-button @click="$router.go(-1)" icon="left" type="text" class="back-button">
        <img src="@/assets/svgs/left.svg" alt="Back" />
      </el-button>
      <span class="title">课堂总结</span>
      <div class="header-right">
        <el-button @click="openDialog" type="text" class="record-button">添加总结</el-button>
      </div>
    </header>
    <div class="record-card-list">
      <div v-for="record in records" :key="record.id" class="record-card">
        <div class="record-title">{{ record.title }}</div>
        <div class="record-keywords">
          <span v-for="keyword in record.keywords" :key="keyword" class="keyword">{{ keyword }}</span>
        </div>
        <div class="record-summary">{{ record.summary }}</div>
        <div class="record-dates">{{ formatDate(record.publishTime) }}</div>
      </div>
    </div>

    <!-- 上传音视频文件对话框 -->
    <el-dialog title="上传音视频文件" v-model="dialogVisible" width="600px" append-to-body>
      <hr class="dialog-divider" />
      <div class="dialog-content" style="margin-bottom: 30px;">
        <el-upload class="upload-demo" :auto-upload="false" :on-change="(file) => uploadFile = file" :limit="1"
          accept=".mp4,.wmv,.m4v,.flv,.rmvb,.dat,.mov,.mkv,.webm,.avi,.mpeg,.3gp,.ogg,.mp3,.wav,.m4a,.wma,.aac,.amr,.flac,.aiff">
          <el-button type="primary" class="upload-button" :loading="isUploading">上传</el-button>
        </el-upload>
      </div>
      <div class="dialog-info" style="margin-top: 30px; text-align: left;">单个文件最长六小时</div>
      <div class="dialog-info" style="text-align: left;">
        视频支持：mp4/wmv/m4v/flv/rmvb/dat/mov/mkv/webm/avi/mpeg/3gp/ogg，单个最大 6G</div>
      <div class="dialog-info" style="text-align: left;">音频支持：mp3/wav/m4a/wma/aac/ogg/amr/flac/aiff，单个最大 500M</div>
      <div class="dialog-actions" style="margin-top: 40px;">
        <el-button @click="dialogVisible = false" class="cancel-button" style="border-color: #13227a;">取消</el-button>
        <el-button type="primary" class="transcribe-button" style="border-color: #13227a;" @click="startTranscribe"
          :disabled="!uploadFile">开始转写</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { useRoute } from 'vue-router';
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import axios from 'axios';

const route = useRoute();
const recordId = route.params.id; // 获取反馈 ID
const dialogVisible = ref(false);
const uploadFile = ref(null);
const isUploading = ref(false);
const records = ref([]);

function formatDate(date) {
  const options = { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hour12: false };
  return new Intl.DateTimeFormat('zh-CN', options).format(date);
}

function openDialog() {
  dialogVisible.value = true; // 打开对话框
}

function addRecord() {
  const newRecord = {
    id: records.length + 1,
    publishTime: new Date(),
    keywords: ['关键词1', '关键词2'], // 示例关键词
    summary: '课程内容的总结浓缩', // 示例总结
    submittedCount: 0,
    totalCount: 30
  };
  records.value.push(newRecord);
}

// 模拟数据
const mockRecords = [
  {
    id: 1,
    title: '第一节课：Vue基础入门',
    publishTime: new Date('2024-03-15 14:30:00'),
    keywords: ['Vue3', '组件', '响应式'],
    summary: '本节课介绍了Vue3的基础概念，包括组件化开发、响应式系统等核心特性。学生们展现出了浓厚的学习兴趣，课堂互动频繁。',
    submittedCount: 25,
    totalCount: 30
  },
  {
    id: 2,
    title: '第二节课：组件通信',
    publishTime: new Date('2024-03-16 10:00:00'),
    keywords: ['Props', 'Emit', '状态管理'],
    summary: '详细讲解了Vue组件间的各种通信方式，包括props传递、事件触发、状态管理等内容。课堂练习完成情况良好。',
    submittedCount: 28,
    totalCount: 30
  },
  {
    id: 3,
    title: '第三节课：路由和状态管理',
    publishTime: new Date('2024-03-17 15:20:00'),
    keywords: ['Vue Router', 'Pinia', 'Vuex'],
    summary: '介绍了Vue Router的使用方法和Pinia状态管理工具，学生们通过实战项目加深了理解。',
    submittedCount: 22,
    totalCount: 30
  },
  {
    id: 4,
    title: '第四节课：网络请求和异步操作',
    publishTime: new Date('2024-03-18 09:15:00'),
    keywords: ['Axios', 'async/await', 'API'],
    summary: '学习了如何在Vue项目中处理网络请求，使用Axios库进行API调用，以及异步操作的最佳实践。',
    submittedCount: 27,
    totalCount: 30
  },
  {
    id: 5,
    title: '第五节课：性能优化',
    publishTime: new Date('2024-03-19 13:45:00'),
    keywords: ['性能', '懒加载', '缓存'],
    summary: '探讨了Vue应用的性能优化策略，包括组件懒加载、缓存优化、打包优化等话题。',
    submittedCount: 24,
    totalCount: 30
  },
  {
    id: 6,
    title: '第六节课：项目实战',
    publishTime: new Date('2024-03-20 14:00:00'),
    keywords: ['实战', '项目开发', '最佳实践'],
    summary: '通过一个完整的项目实战，综合运用前面所学知识，学生们展示了良好的开发能力。',
    submittedCount: 29,
    totalCount: 30
  }
];

// 修改获取记录列表的函数，使用模拟数据
async function fetchRecords() {
  try {
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 500));
    records.value = mockRecords;
  } catch (error) {
    ElMessage.error('获取记录列表失败');
    console.error(error);
  }
}

// 处理文件上传
async function handleFileUpload(file) {
  if (!validateFile(file)) return false;

  const formData = new FormData();
  formData.append('file', file);

  try {
    isUploading.value = true;
    const response = await axios.post('/api/teacher/records/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
    ElMessage.success('文件上传成功');
    dialogVisible.value = false;
    await fetchRecords(); // 刷新记录列表
  } catch (error) {
    ElMessage.error('文件上传失败');
    console.error(error);
  } finally {
    isUploading.value = false;
  }
}

// 文件验证
function validateFile(file) {
  const videoFormats = ['mp4', 'wmv', 'm4v', 'flv', 'rmvb', 'dat', 'mov', 'mkv', 'webm', 'avi', 'mpeg', '3gp', 'ogg'];
  const audioFormats = ['mp3', 'wav', 'm4a', 'wma', 'aac', 'ogg', 'amr', 'flac', 'aiff'];

  const extension = file.name.split('.').pop().toLowerCase();
  const isValidFormat = [...videoFormats, ...audioFormats].includes(extension);

  if (!isValidFormat) {
    ElMessage.error('不支持的文件格式');
    return false;
  }

  const isVideo = videoFormats.includes(extension);
  const maxSize = isVideo ? 6 * 1024 * 1024 * 1024 : 500 * 1024 * 1024; // 6GB or 500MB

  if (file.size > maxSize) {
    ElMessage.error(isVideo ? '视频文件大小不能超过6GB' : '音频文件大小不能超过500MB');
    return false;
  }

  return true;
}

// 开始转写
async function startTranscribe() {
  if (!uploadFile.value) {
    ElMessage.warning('请先上传文件');
    return;
  }

  try {
    const response = await axios.post('/api/teacher/records/transcribe', {
      fileId: uploadFile.value.id
    });
    ElMessage.success('开始转写，请稍后查看结果');
    dialogVisible.value = false;
    await fetchRecords();
  } catch (error) {
    ElMessage.error('转写失败');
    console.error(error);
  }
}

onMounted(() => {
  fetchRecords();
});
</script>

<script>
export default {
  data() {
    return {
      records: [
        // 示例数据
        {
          id: 1,
          title: '课程标题',
          publishTime: new Date(),
          keywords: ['关键词1', '关键词2'],
          summary: '课程内容的总结浓缩',
          submittedCount: 5,
          totalCount: 30
        },
        // 可以添加更多记录
      ]
    };
  }
};
</script>

<style scoped>
.template {
  background-color: #F9FAFB;
}

.header {
  color: white;
  padding: 10px;
  display: flex;
  align-items: center;
  background-color: #13227a;
  justify-content: space-between;
  /* 使内容两端对齐 */
}

.back-button {
  color: white;
  border: none;
  width: 25px;
  height: 25px;
}

.title {
  margin-left: 10px;
  /* 添加左边距 */
}

.header-right {
  display: flex;
  /* 使右侧内容为flex布局 */
}

.record-button {
  background-color: #13227a;
  border: 1px solid white;
  color: white;
  width: 120px;
  height: 40px;
}

.record-card-list {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  margin-top: 20px;
  padding: 0 40px;
}

.record-card {
  background-color: white;
  border: 1px solid #ccc;
  border-radius: 5px;
  padding: 10px;
  height: 220px;
  /* 调整每个卡片的大小 */
  width: calc(30% - 15px);
  /* 调整为一行三张卡片 */
  margin-bottom: 15px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.record-title {
  font-weight: bold;
  color: black;
  font-size: 20px;
}

.record-keywords {
  margin-top: 10px;
}

.keyword {
  color: #13227a;
  background-color: rgba(19, 34, 122, 0.1);
  border-radius: 5px;
  padding: 5px;
  margin-right: 5px;
  display: inline-block;
}

.record-summary {
  margin-top: 10px;
  color: darkgray;
}

.record-dates {
  color: gray;
  font-size: 14px;
  margin-top: auto;
  /* 使时间在卡片右下角 */
}

.dialog-divider {
  border: 1px solid lightgray;
}

.dialog-content {
  text-align: center;
}

.upload-button {
  background-color: #13227a;
  color: white;
  border-color: #13227a;
  /* 添加边框颜色 */
}

.upload-button:active {
  background-color: #13227a;
  /* active状态颜色 */
  opacity: 0.8;
}

.dialog-info {
  margin-top: 10px;
  text-align: left;
}

.dialog-actions {
  margin-top: 20px;
  text-align: right;
}

.cancel-button {
  color: #13227a;
  border-color: #13227a;
}

.cancel-button:active {
  background-color: #13227a;
  /* active状态颜色 */
  opacity: 0.8;
}

.transcribe-button {
  background-color: #13227a;
  color: white;
  border-color: #13227a;
}

.transcribe-button:active {
  background-color: #13227a;
  /* active状态颜色 */
  opacity: 0.8;
}
</style>